package com.atom.common.dao.dj;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.atom.common.dao.AvensCommonDao;
import com.atom.common.entity.dj.DjFileDO;
import com.atom.common.exception.AvensNullPointerException;
import com.atom.common.remote.file.RemoteFileDao;
import com.atom.common.remote.user.UserUtil;
import com.atom.common.util.PreConditionUtil;

@Repository
public class DjFileDao extends AvensCommonDao<DjFileDO> {

  @Resource RemoteFileDao remoteFileDao;
  
  public void addFile(int fileType, String taskId, String processInstanceId, String fileName, 
      String key, String fileSize ,UserUtil user) {
    DjFileDO file = new DjFileDO();
    file.setProcessInstanceId(processInstanceId);
    file.setTaskId(taskId);
    file.setFileName(fileName);
    file.setFileKey(key);
    file.setFileSize(fileSize);
    file.setFileType(fileType);
    file.setDisabled(false);
    file.setCreateTime(new Date());
    file.setCreateUser(user.getUserid());
    file.setCreateUserText(user.getUsername());
    super.save(file);
  }
  
  public void deleteFile(String key) {
    PreConditionUtil.checkNotNull(key, "file key cannot be null");
    
    List<DjFileDO> list = super.findByProperty("fileKey", key);
    if (list == null || list.size() == 0) {
      throw new AvensNullPointerException("cannot find file where key : " + key);
    }
    DjFileDO DjFileDO = list.get(0);
    DjFileDO.setDisabled(true);
    super.update(DjFileDO);
  }


  public List<DjFileDO> findByTypeByProcessInstanceId(int fileType, String processInstanceId) {
    Map<String, Object> vars = new HashMap<String, Object>();
    vars.put("fileType", fileType);
    vars.put("processInstanceId", processInstanceId);
    vars.put("disabled", false);
    return super.findByProperties(vars);
  }

}
